package com.ve.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class FileUtils {
    private static final String TAG = FileUtils.class.getSimpleName();

    public static void unZip(AssetManager assetManager, String assetName, String outputDirectory, boolean isReWrite) throws IOException {
        File file = new File(outputDirectory);
        if (!file.exists()) {
            file.mkdirs();
        }
        InputStream inputStream = assetManager.open(assetName);
        ZipInputStream zipInputStream = new ZipInputStream(inputStream);

        byte[] buffer = new byte[1024 * 1024];
        for (ZipEntry zipEntry = zipInputStream.getNextEntry(); zipEntry != null; zipEntry = zipInputStream.getNextEntry()) {

            file = new File(outputDirectory + File.separator + zipEntry.getName());
            if (!isReWrite && file.exists()) {
                Log.d(TAG, "skip: " + file.getPath());
                continue;
            }

            Log.d(TAG, "unzip: " + file.getPath());

            if (zipEntry.isDirectory()) {
                file.mkdir();
            } else {
                file.createNewFile();
                FileOutputStream fileOutputStream = new FileOutputStream(file);

                int count;
                while ((count = zipInputStream.read(buffer)) > 0) {
                    fileOutputStream.write(buffer, 0, count);
                }
                fileOutputStream.close();

            }

        }
        zipInputStream.close();
    }


    public static void copy(Context context, String name, String path) {
        String filename = path + "/" + name;
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdir();
        }
        try {
            AssetManager assetManager = context.getResources().getAssets();
            if (!(new File(filename)).exists()) {
                InputStream is = assetManager.open(name);
                FileOutputStream fos = new FileOutputStream(filename);
                byte[] buffer = new byte[4096];
                int count = 0;
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                fos.close();
                is.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
